package util;

import static util.Debug.log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;

import javax.microedition.io.StreamConnection;

public class RFCOMMInputStream extends BufferedReader	{
	private static final long INTERVAL 			= 50;
	private static final long TIMEOUT  			= 500;
	private static final int  MAX_LINE_LENGTH 	= 255;
		
	public RFCOMMInputStream(StreamConnection con)	throws IOException{
		super(new InputStreamReader(con.openInputStream()));
		
		ignoreList = new HashSet<String>();
	}
	
	private HashSet<String> ignoreList;
	
	public void ignoreString(String ignore)	{
		ignoreList.add(ignore);
	}
	
	// @TODO refactor this method to be more readable
	public String readLine()	throws IOException	{
		char outputBuffer[] = new char[MAX_LINE_LENGTH];
		int offset = 0;
		long time = TIMEOUT;
		
		while(time > 0)	{
			if(ready())	{
				char currentChar = (char) super.read();
				
				// End of string character in this case is a useless prompt so ignore - may cause 
				// problems in the future if this class is reused! here is what needs changing
				// in that case
				if (currentChar == -1)	{
					// Drop out and do the same thing as a timeout as they signify the
					// same thing - no more data to come
					break;
				}
				// These things imply the end of a line and should induce a line return
				else if (currentChar == '\n' || offset == MAX_LINE_LENGTH)	{
					// Finalise line
					String line = new String(outputBuffer, 0, offset);
					
					// If it is non blank and doesn't contain an unwanted line return it
					if(offset > 0 && ! ignoreList.contains(line))	{
						return line;
					}
					else	{
						// zero length string! reset and keep looking
						outputBuffer = new char[MAX_LINE_LENGTH];
						offset = 0;
					}
				}
				// Exclude certain characters entirely
				else if (currentChar == '\r' || (offset == 0 && currentChar == '>'))	{
					// Do nothing, just ignore
				}
				// And if none of that is the case it's a perfectly normal character and should be added
				else	{
					// Add char to buffer
					//log("adding char " + (int) currentChar + currentChar);
					outputBuffer[offset] = currentChar;
					offset++;
				}
			}
			else	{
				// Wait a bit...
				time -= INTERVAL;
				try {
					Thread.sleep(INTERVAL);
				} catch (InterruptedException e) {
					log(e.getMessage());
				}
			}
		}
		return null;
	}
}
